package com.seeyon.apps.seepkk.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jersey.repackaged.com.google.common.collect.Maps;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.kk.constants.Constants;
import com.seeyon.apps.kk.controller.KkBaseController;
import com.seeyon.apps.kk.manager.FreemarkFlowManager;
import com.seeyon.apps.kk.util.JdbcAgentUtil;
import com.seeyon.apps.seepkk.manager.SeepManager;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.po.template.CtpTemplate;
import com.seeyon.ctp.util.FlipInfo;

public class SeepKKController extends KkBaseController {
	private FreemarkFlowManager freemarkFlowManager;
	private SeepManager seepManager =(SeepManager) AppContext.getBean("seepManager");

	/**
	 * Seep模块开发相关配置
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public void seepConfig(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8");
		String formName=request.getParameter("formName");
		String path = "seep" + File.separator + "formConfig.ftl";
		JSONArray aryData = (JSONArray) JSONArray.parse(this.freemarkFlowManager.fltTemplateIntoString(path, null));
		JSONArray aryConfig = new JSONArray();
		for (int i = 0; i < aryData.size(); i++) {
			JSONObject obj = aryData.getJSONObject(i);
			if(formName.equals(obj.getString("formName"))){
				FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
				FormBean formByFormCode2 = formApi4Cap4.getFormByFormCode(obj.getString("formCode"));
				List<FormTableBean> tableList = formByFormCode2.getTableList();
				for (FormTableBean formTableBean : tableList) {
					if (formTableBean.getDisplay().contains("会议日程")) {
						obj.put("frontTable", formTableBean.getFrontTableName());
						obj.put("startDateCode", nameToFiled(formTableBean, "会议开始时间"));
						obj.put("endDateCode", nameToFiled(formTableBean, "会议结束时间"));
						obj.put("nameCode", nameToFiled(formTableBean, "提供者编号"));
					}
					if (formTableBean.getDisplay().contains("专家信息")) { 
						obj.put("expertTypeCode", nameToFiled(formTableBean, "专家服务类型"));
						obj.put("memberTypeCode", nameToFiled(formTableBean, "隐藏讲者类别"));
					}
				}
				aryConfig.add(obj);
			}
			
		}
		response.getWriter().print(aryConfig);
	}

	/**
	 * Seep会议日程报表页面
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView meetingReport(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("plugin/kk/serjs/meeting");
		String formmainId = request.getParameter("formmainId");
		String contentTemplateId = request.getParameter("contentTemplateId");
		mav.addObject("formmainId", formmainId);
		mav.addObject("contentTemplateId", contentTemplateId);
		return mav;
	}

	/**
	 * 查询更多
	 */
	public void queryMeeting(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			String formmainId = request.getParameter("formmainId");
			String contentTemplateId = request.getParameter("contentTemplateId");
			// PT活动申请表中的会议日程重复表数据
			FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
			FormBean formByFormCode2 = formApi4Cap4.getForm(Long.valueOf(contentTemplateId));
			List<FormTableBean> tableList = formByFormCode2.getTableList();
			FormTableBean masterTableBean2 = new FormTableBean();
			for (FormTableBean formTableBean : tableList) {
				if (formTableBean.getDisplay().contains("会议日程")) {
					masterTableBean2 = formTableBean;
					break;
				}

			}
			StringBuilder sql = new StringBuilder();
			sql.append("select sort as 序号,enum1.SHOWVALUE as 会议会场,CONVERT(varchar(100),"
					+ nameToFiled(masterTableBean2, "会议开始时间") + ", 20) as 会议开始时间,");
			sql.append(" CONVERT(varchar(100), " + nameToFiled(masterTableBean2, "会议结束时间") + ", 20) as 会议结束时间,");
			sql.append(" " + nameToFiled(masterTableBean2, "分钟") + " as 分钟," + nameToFiled(masterTableBean2, "日程描述")
					+ " as 日程描述	,enum2.SHOWVALUE as 讲者类别,enum3.SHOWVALUE as 服务类型,"
					+ nameToFiled(masterTableBean2, "提供者") + " as 提供者 from " + masterTableBean2.getTableName());
			sql.append(" left outer join CTP_ENUM_ITEM enum1 on enum1.id=" + nameToFiled(masterTableBean2, "会议会场"));
			sql.append(" left outer join CTP_ENUM_ITEM enum2 on enum2.id=" + nameToFiled(masterTableBean2, "讲者类别"));
			sql.append(" left outer join CTP_ENUM_ITEM enum3 on enum3.id=" + nameToFiled(masterTableBean2, "服务类型"));
			sql.append(" where formmain_Id=:formmain_Id order by sort");
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("formmain_Id", formmainId);
			List<Map> datList = JdbcAgentUtil.doQuery(sql.toString(), params);
			String data = JSONArray.toJSONString(datList);
			response.getWriter()
					.print("{\"code\":0,\"msg\":\"\",\"count\":" + datList.size() + ",\"data\":" + data + "}");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 关联底表自定义控件数据回填
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public void dataBack(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8");
		String tableCode = request.getParameter("tableCode");
		String activityNo = request.getParameter("activityNo");
		FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
		FormBean formBean = formApi4Cap4.getFormByFormCode(tableCode);
		Map<String, Object> params = Maps.newHashMap();
		params.put("activityNo", activityNo);
		Map<String, Object> result = this.seepManager.customControlDataBack(formBean, params);
		response.getWriter().print(JSON.toJSON(result));
	}
	
	
	/**
	 * 表单水印内容获取
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws Exception
	 */
	public void formWarteMark(HttpServletRequest request, HttpServletResponse response) throws IOException{
		try {
			request.setCharacterEncoding("utf-8");
			response.setContentType("application/json;charset=utf-8");
			String fromRecordId = request.getParameter("fromRecordId");
			String templateId = request.getParameter("templateId");
			String result="";
			FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
			if(StringUtils.isNotEmpty(fromRecordId)&&StringUtils.isNotEmpty(fromRecordId)){
				//当前表单模版编号
				CtpTemplate ctpTemplate =templateManager.getCtpTemplate(Long.valueOf(templateId));
				if(StringUtils.isNotEmpty(ctpTemplate.getTempleteNumber())){
					//根据模版编号查询配置表
					FlipInfo flipInfo = new FlipInfo(1, 20);
					FormBean bean = formApi4Cap4.getFormByFormCode(Constants.waterFormCode);
					Map<String, Object> where = new HashMap<String, Object>();
					where.put(bean.getFieldBeanByDisplay("表单模版编号").getName(), ctpTemplate.getTempleteNumber());
					List<FormDataMasterBean> masterList = formApi4Cap4.findMasterDataList(flipInfo , bean .getId(), null, where );
					if(!masterList.isEmpty()){
						if(Long.valueOf(masterList.get(0).getFieldValue(bean.getFieldBeanByDisplay("人员姓名").getName()).toString())==-4504399432329772408L){
							result+=AppContext.currentUserName();
						};
						if(!StringUtils.isEmpty(masterList.get(0).getFieldValue(bean.getFieldBeanByDisplay("表单字段").getName()).toString())){
							//表单字段值
							String fileName=masterList.get(0).getFieldValue(bean.getFieldBeanByDisplay("表单字段").getName()).toString();
							String formCode=masterList.get(0).getFieldValue(bean.getFieldBeanByDisplay("表单模版编号").getName()).toString();
							FormBean tableBean = formApi4Cap4.getFormByFormCode(formCode);
							FormDataMasterBean masterList2 = formApi4Cap4.findDataById(Long.valueOf(fromRecordId), tableBean.getId(), null);
							result+=" "+masterList2.getFieldValue(tableBean.getFieldBeanByDisplay(fileName).getName());
						}
						if(Long.valueOf(masterList.get(0).getFieldValue(bean.getFieldBeanByDisplay("系统时间").getName()).toString())==-4504399432329772408L){
							String nowDate=DateFormatUtils.format(new Date(), "yyyy-MM-dd");
							result+=" "+nowDate; 
						};
					}
				}
			}
			response.getWriter().print(result);
		} catch (Exception e) {
			response.getWriter().print("");
		}
	}
	/**
	 * IO号批量生成
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws Exception
	 */
	public void ioCreate(HttpServletRequest request, HttpServletResponse response) throws IOException{
		try {
			request.setCharacterEncoding("utf-8");
			response.setContentType("application/json;charset=utf-8");
			String startIO = request.getParameter("startIO");
			String endIO = request.getParameter("endIO");
			String companyCode = request.getParameter("companyCode");
			String result=this.seepManager.ioCreate(startIO, endIO, companyCode);
			response.getWriter().print(result);
		} catch (Exception e) {
			logger.error("seepkk-IO号生成异常", e);
			response.getWriter().print( "IO号生成异常，请联系管理员"+e.toString());
		}
	}
	
	public void syncMdmStatus(HttpServletRequest request, HttpServletResponse response) throws Exception{
			request.setCharacterEncoding("utf-8");
			response.setContentType("application/json;charset=utf-8");
			this.seepManager.syncAttend();
			response.getWriter().print("sync ok!");
	}
	
	
	
	
	public static String nameToFiled(FormTableBean formTableBean, String fileName) {
		return formTableBean.getFieldBeanByDisplay(fileName).getName();
	}

	public FreemarkFlowManager getFreemarkFlowManager() {
		return freemarkFlowManager;
	}

	public void setFreemarkFlowManager(FreemarkFlowManager freemarkFlowManager) {
		this.freemarkFlowManager = freemarkFlowManager;
	}
	public static void main(String[] args) {
		String a="wtt";
		System.out.println(a.contains("1"));
	}
}
